﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Web;
using System.Xml;
using Yunzuan.Common.Log;
using Yunzuan.Foundation.DataAccess;
using YunZuan.Models.Entities;
using Yunzuan.Foundation.Log;
using Yunzuan.Foundation.Serializer;
using Yunzuan.Foundation.Web;
using Yunzuan.Foundation.Web_api;
using YunZuan.Models;
using YunZuan.Models.Supplier;

namespace Yunzuan.Common.Interface
{

    /// <summary>
    /// 上传文件结果
    /// </summary>
    [MessageContract]
    public class UpFileResult
    {
        [MessageHeader]
        public bool IsSuccess { get; set; }
        [MessageHeader]
        public string Message { get; set; }

    }

    /// <summary>
    /// 上传文件
    /// </summary>
    [MessageContract]
    public class FileUploadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public string FileName;//文件名（类似键）

        [MessageBodyMember(Order = 1)]
        public Stream FileData;//文件流（类似值）

        [MessageHeader]
        public string key;

        [MessageHeader]
        public string url;

        [MessageHeader]
        public string GoodsType;
    }
    /// <summary>
    /// 上传图片
    /// </summary> 
    [MessageContract, KnownType(typeof(ImageMessage))]
    public class ImageUploadMessage
    {
        [MessageHeader(MustUnderstand = true)]
        public string TypeName;//类型名

        [MessageHeader]
        public ImageMessage[] ImageDatas; //文件集合

        [MessageHeader]
        public string key;

        [MessageHeader]
        public string type;
    }
    /// <summary>
    /// 单个文件
    /// </summary>
    [DataContract]
    public class ImageMessage
    {
        [DataMember(Name = "FileName", Order = 1)]
        public string FileName { get; set; }//文件名（类似键）

        [DataMember(Name = "ImageData", Order = 2)]
        public byte[] ImageData { get; set; }//代替文件流（类似值）
    }
    /// <summary>
    /// 公共接口实现
    /// </summary>
    public class AllPublic
    {


        #region /////************银行相关*****************
        /// <summary>
        /// 修改银行账户 12-13
        /// </summary>
        /// <param name="editBankParam"></param>
        /// <returns></returns>
        public static string EditBank(string editBankParam)
        {
            string logParam = editBankParam;
            string tttagKey = CommonUrl.getURL(null, editBankParam, "修改银行账户");
            //BankID（必传）
            BankInfo param = Json.Deserialize<BankInfo>(editBankParam);
            try
            {
                param.CheckTime = DateTime.Now;//对账时间
                using (ITransaction trans_editBank = YZ.GetTransaction(tttagKey))
                {
                    int editBankResult = trans_editBank.Edit(param);
                    if (editBankResult > 0)
                    {
                        try
                        {
                            trans_editBank.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("操作成功");
                        }
                        catch (Exception e)
                        {
                            trans_editBank.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("操作失败");
                        }
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("操作失败");
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：修改银行账户" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        public static string ModifyExchange(string modifyExchangeParam)
        {
            var logParam = modifyExchangeParam;
            HashParam param = Json.Deserialize<HashParam>(modifyExchangeParam);
            string tttagKey = CommonUrl.getURL(param, modifyExchangeParam);
            //{"ExBankID":"11","BankID":"19","Others":"","Exchange":"6.15","Remarks":"","ExBalance":"5000","Amount":"30750","ExAmount":"3000","UserID":712}           
            //templateJSON
            try
            {
                //1.更新国内支出账户结余-支出(BankID)
                BankInfo _bank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("BankID"));
                #region
                if (_bank != null)
                {
                    if (_bank.CheckResult == 0)
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("支出账户对账不符，请先对账");
                    }
                    BankInfo _bankInfo = new BankInfo();
                    _bankInfo.BankID = _bank.BankID;//支出账户
                    _bankInfo.UpdateTime = DateTime.Now;
                    //ExAmount 实支付金额
                    if ((_bank.BankBalance + (-param.GetDecimal("ExAmount"))) >= 0)
                    {
                        //支出账户能够支付实支出金额
                        _bankInfo.BankBalance = _bank.BankBalance + (-param.GetDecimal("ExAmount"));//实支出金额
                    }
                    else
                    {
                        //跳出
                        return CommonLog.MsgErrorInfo("支出账户结余不足,请先入账");
                    }
                    using (ITransaction trans_modExchange = YZ.GetTransaction(tttagKey))
                    {
                        int editBankBalanceResult = trans_modExchange.Edit(_bankInfo);//更新账户结余 -只能用Edit
                        if (editBankBalanceResult > 0)
                        {
                            //2.添加支出已审核记录
                            #region
                            FlowInfo _flowInfo = new FlowInfo();
                            _flowInfo.Account = _bankInfo.BankID;
                            _flowInfo.Amount = param.GetDecimal("ExAmount");//实支出
                            _flowInfo.Receivable = param.GetDecimal("Amount") * param.GetDecimal("Exchange");//应支出 = 已兑换美金 * 兑换汇率
                            _flowInfo.Balance = _bankInfo.BankBalance;
                            _flowInfo.Currency = _bank.Currency;//1人民币 2美金
                            _flowInfo.Status = 1;//1已审核
                            _flowInfo.Type = 2;//2支出
                            _flowInfo.ApplyID = param.GetInt("UserID");
                            _flowInfo.ReviewID = param.GetInt("UserID");
                            _flowInfo.Comments = param.GetString("Comments");
                            _flowInfo.Remarks = "兑换美金";
                            _flowInfo.Purpose = 2;//2换美金
                            _flowInfo.Abstract = 9;//9 兑换美金
                            _flowInfo.ArrivalTime = param.GetDataTime("ArrivalTime");//到账日期 2017-03-06
                            _flowInfo.CreateTime = DateTime.Now;
                            _flowInfo.UpdateTime = DateTime.Now;
                            int addFlowResult = trans_modExchange.Add(_flowInfo);
                            if (addFlowResult > 0)
                            {
                                //更新RMB-支出账户结余ExBankID
                                #region
                                BankInfo _expensebank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByAccount", param.GetInt("ExBankID"));
                                if (_expensebank != null)
                                {
                                    if (_expensebank.CheckResult == 0)
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("支出账户对账不符，请先对账");
                                    }
                                    BankInfo _expenseBankInfo = new BankInfo();
                                    _expenseBankInfo.BankID = _expensebank.BankID;//支出账户
                                    //差额 = 实支出金额ExAmount 和 已兑换美金Amount * 兑换汇率Exchange 之差;
                                    _expenseBankInfo.BankBalance = _expensebank.BankBalance + (param.GetDecimal("ExAmount") + (-(param.GetDecimal("Amount") * param.GetDecimal("Exchange"))));
                                    _expenseBankInfo.UpdateTime = DateTime.Now;
                                    int editexpenseBankBalanceResult = trans_modExchange.Edit(_expenseBankInfo);//更新账户结余 -只能用Edit
                                    if (editexpenseBankBalanceResult > 0)
                                    {
                                        //添加流水记录
                                        #region
                                        FlowInfo _expflowInfo = new FlowInfo();
                                        _expflowInfo.Account = _expensebank.BankID;
                                        _expflowInfo.Amount = Math.Abs(Convert.ToDecimal(param.GetDecimal("ExAmount") + (-(param.GetDecimal("Amount") * param.GetDecimal("Exchange")))));//支出差额(正值) 应付-实付
                                        _expflowInfo.Balance = _expensebank.BankBalance + (param.GetDecimal("ExAmount") + (-(param.GetDecimal("Amount") * param.GetDecimal("Exchange"))));
                                        _expflowInfo.Currency = _expensebank.Currency;//1人民币 2美金
                                        _expflowInfo.Status = 1;//1已审核
                                        if ((param.GetDecimal("ExAmount") + (-(param.GetDecimal("Amount") * param.GetDecimal("Exchange")))) < 0)
                                        {
                                            _expflowInfo.Type = 2;//2支出
                                        }
                                        else
                                        {
                                            _expflowInfo.Type = 1;//1收入
                                        }
                                        _expflowInfo.ApplyID = param.GetInt("UserID");
                                        _expflowInfo.ReviewID = param.GetInt("UserID");
                                        _expflowInfo.Comments = param.GetString("Comments");
                                        _expflowInfo.Remarks = "兑换美金";
                                        _expflowInfo.Purpose = 2;//2换美金
                                        _expflowInfo.Abstract = 9;//9 兑换美金
                                        _expflowInfo.ArrivalTime = param.GetDataTime("ArrivalTime");//到账日期 2017-03-06
                                        _expflowInfo.CreateTime = DateTime.Now;
                                        _expflowInfo.UpdateTime = DateTime.Now;
                                        int addExpFlowResult = trans_modExchange.Add(_expflowInfo);
                                        if (addExpFlowResult > 0)
                                        {
                                            //3.更新收入Type=2账户结余+
                                            #region
                                            BankInfo _exBank = YZ.GetDatabase(tttagKey).QueryForObject<BankInfo>("Bank.GetBankByType", 2);
                                            if (_exBank != null)
                                            {
                                                if (_exBank.CheckResult == 0)
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("收入账户对账不符，请先对账");
                                                }
                                                BankInfo _exbankInfo = new BankInfo();
                                                _exbankInfo.BankID = _exBank.BankID;//收入账户
                                                _exbankInfo.BankBalance = _exBank.BankBalance + (param.GetDecimal("Amount"));//已兑换美金Amount
                                                _exbankInfo.UpdateTime = DateTime.Now;
                                                int editExBankBalanceResult = trans_modExchange.Edit(_exbankInfo);//更新账户结余 -只能用Edit
                                                if (editExBankBalanceResult > 0)
                                                {
                                                    //4.添加收入已审核记录
                                                    FlowInfo _exflowInfo = new FlowInfo();
                                                    _exflowInfo.Account = _exbankInfo.BankID;
                                                    _exflowInfo.Amount = param.GetDecimal("Amount");//本次兑换美金
                                                    _exflowInfo.Balance = _exbankInfo.BankBalance;
                                                    _exflowInfo.Currency = _exBank.Currency;//2美金
                                                    _exflowInfo.Status = 1;//1已审核
                                                    _exflowInfo.Type = 1;//1收入
                                                    _exflowInfo.Others = param.GetString("Others");
                                                    _exflowInfo.ApplyID = param.GetInt("UserID");
                                                    _exflowInfo.ReviewID = param.GetInt("UserID");
                                                    _exflowInfo.Comments = param.GetString("Comments");
                                                    _exflowInfo.Remarks = "兑换美金";
                                                    _exflowInfo.Purpose = 2;//2换美金
                                                    _exflowInfo.Abstract = 9;//9 兑换美金
                                                    _exflowInfo.ArrivalTime = param.GetDataTime("ArrivalTime");//到账日期 2017-03-06
                                                    _exflowInfo.CreateTime = DateTime.Now;
                                                    _exflowInfo.UpdateTime = DateTime.Now;
                                                    int addExFlowResult = trans_modExchange.Add(_exflowInfo);
                                                    if (addExFlowResult > 0)
                                                    {
                                                        //5.添加兑换记录
                                                        ExchangeInfo _exchangeInfo = Json.Deserialize<ExchangeInfo>(modifyExchangeParam);
                                                        _exchangeInfo.Remarks = param.GetString("Comments");
                                                        //_exchangeInfo.CreateTime = DateTime.Now;
                                                        _exchangeInfo.CreateTime = param.GetDataTime("CreateTime");//2017-02-23
                                                        int addExchangeResult = trans_modExchange.Add(_exchangeInfo);
                                                        if (addExchangeResult > 0)
                                                        {
                                                            //继续
                                                        }
                                                        else
                                                        {
                                                            //跳出
                                                            return CommonLog.MsgErrorInfo("添加兑换记录失败");
                                                        }
                                                    }
                                                    else
                                                    {
                                                        //跳出
                                                        return CommonLog.MsgErrorInfo("添加收入流水失败");
                                                    }
                                                }
                                                else
                                                {
                                                    //跳出
                                                    return CommonLog.MsgErrorInfo("更新账户结余失败");
                                                }
                                            }
                                            else
                                            {
                                                //跳出
                                                return CommonLog.MsgErrorInfo("收入账户不存在,请检查标识");
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            //跳出
                                            return CommonLog.MsgErrorInfo("添加支出流水失败");
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        //跳出
                                        return CommonLog.MsgErrorInfo("更新账户结余失败");
                                    }
                                }
                                else
                                {
                                    //RMB-支出账户不存在
                                }
                                #endregion
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("添加支出流水失败");
                            }
                            #endregion
                        }
                        else
                        {
                            //跳出
                            return CommonLog.MsgErrorInfo("更新账户结余失败");
                        }
                        //事务
                        try
                        {
                            //提交事务
                            trans_modExchange.CommitTransaction();
                            return CommonLog.MsgSuccessInfo("兑换成功");
                        }
                        catch (Exception)
                        {
                            //回滚事务
                            trans_modExchange.RollBackTransaction();
                            return CommonLog.MsgErrorInfo("兑换失败");
                        }
                    }
                }
                else
                {
                    //跳出
                    return CommonLog.MsgErrorInfo("支出账户不存在,请检查标识");
                }
                #endregion
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #endregion

        #region &&&&&&&&&&&&&&&&&&&&&&&&上传相关&&&&&&&&&&&&&&&&&&&&&&&&
        /// <summary>
        /// 上传模式（0覆盖 1追加）
        /// </summary>
        public static string UploadFileState(string uploadFileStateParam)
        {
            var logParam = uploadFileStateParam;
            HashParam param = Json.Deserialize<HashParam>(uploadFileStateParam);
            string tttagKey = CommonUrl.getURL(param, uploadFileStateParam);
            try
            {
                string StateId = param.GetString("State");// 0 和 1
                HttpRuntime.Cache.Insert("StateId" + tttagKey, StateId, null, DateTime.Now.AddSeconds(GlobalConfig.ExpirationTimeOut), TimeSpan.Zero);
                return CommonLog.MsgSuccessInfo("切换成功");
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：上传模式（0覆盖 1追加）" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("切换失败");
            }
        }
        #endregion

        #region GetMethodInfoAndWriteLogs
        public static void GetMethodInfoAndWriteLogs(Exception ex)
        {
            CommonLog.GetMethodInfoAndWriteLogs(typeof(AllPublic), ex);
        }
        #endregion


        #region  订单相关
        /// <summary>
        /// 提交订单  删除订单 获取订单 （公共方法）
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="action"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static TransmissionOrderResult OprationOrders(int[] ids, string action, string key, int count = 3)
        {
            StringBuilder sbIds = new StringBuilder();
            try
            {
                if (count > 0)
                {
                    TransmissionOrderResult tor = new TransmissionOrderResult();
                    count--;
                    for (int i = 0; i < ids.Length; i++)
                    {
                        sbIds.Append(ids[i] + ",");
                    }
                    Dictionary<string, object> postData = new Dictionary<string, object>();
                    var strIds = sbIds.ToString().TrimEnd(',');
                    postData["id"] = strIds;
                    int totalSeconds;
                    string signStr;
                    var guid = Guid.NewGuid().ToString();
                    var lastStr = MyHttpRequest.ShotDic1(postData);
                    MyHttpRequest.SignByParams(guid, lastStr.ToString(), key, out totalSeconds, out signStr);
                    RequestInfo rif = new RequestInfo() { RequestJson = JsonConvert.SerializeObject(postData), RequestUrl = GlobalConfig.OUrl + "?id=" + strIds };
                    string returnJson = "";
                    if (action.ToLower() == "add")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST);  //提交订单
                    else if (action.ToLower() == "get")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET);  //获取订单
                    else if (action.ToLower() == "del")
                        returnJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.DELETE);  //删除订单
                    if (returnJson.Contains(".py") && returnJson.Contains("Error:"))
                    {
                        tor.MessageInfo = "远程接口出错,出错信息：" + returnJson.Substring(returnJson.IndexOf("Error:") + 6, returnJson.Length - (returnJson.IndexOf("Error:") + 6));
                        return tor;
                    }
                    else
                    {
                        tor = JsonConvert.DeserializeObject<TransmissionOrderResult>(returnJson);  //返回成功订单ID
                        if (action.ToLower() == "get")
                        {
                            tor.MessageInfo = returnJson; //获取订单的详情
                        }
                        return tor;
                    }
                }
                else
                {
                    TransmissionOrderResult tor = new TransmissionOrderResult() { Result = false, MessageInfo = "网络连接失败" };
                    CommonLog.SendMQMsg("网络连接失败", "异常信息：" + sbIds);
                    return tor;
                }
            }
            catch (Exception ee)
            {
                CommonLog.SendMQMsg(key, "数据中心异常" + ee.StackTrace + "======sbIds:" + sbIds);
                Thread.Sleep(1000 * count); //当数据中心出现网络问题时休眠几秒再试
                //Logger.Error(this.GetType(), "method:OprationOrders," + ee.Message + ",sbIds:" + sbIds);
                GetMethodInfoAndWriteLogs(ee);
                return OprationOrders(ids, action, key, count);
            }
        }
        /// <summary>
        /// 修改订单运费￥ 11-11
        /// </summary>
        /// <param name="freightParam"></param>
        /// <returns></returns>
        public static string ModFreight<T>(string freightParam) where T : BaseEntity
        {
            var logParam = freightParam;
            HashParam param = Json.Deserialize<HashParam>(freightParam);
            string tttagKey = CommonUrl.getURL(param, freightParam, "修改订单运费");
            //OrderIDs（必传）、Freight(默认值,必填)
            try
            {
                if (param.GetString("OrderIDs") == "")
                {
                    return CommonLog.MsgErrorInfo("请先勾选订单");
                }
                else if (param.GetDecimal("Freight") < 0)
                {
                    return CommonLog.MsgErrorInfo("运费不能小于0");
                }
                else
                {
                    string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                    using (ITransaction trans_modFreight = YZ.GetTransaction(tttagKey))
                    {
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            var order = new
                            {
                                OrderID = Convert.ToInt32(_orderIDs[i]),
                                Freight = Convert.ToDecimal(param.GetDecimal("Freight"))
                            };
                            T _order = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(order));
                            int modFreightResult = trans_modFreight.Edit(_order);//这里有个坑 为0
                            if (modFreightResult > 0)
                            {
                                //继续
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("修改运费失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_modFreight.CommitTransaction(); //触发入库事务
                            CommonLog.SendMQMsg(tttagKey, "修改运费成功：" + freightParam);
                            return CommonLog.MsgSuccessInfo("修改运费成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            CommonLog.SendMQMsg(tttagKey, "异常信息：修改运费1" + ex.StackTrace + "参数:" + logParam);
                            trans_modFreight.RollBackTransaction();//回滚事务
                            return CommonLog.MsgErrorInfo("修改失败,请重试");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：修改运费2" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        /// <summary>
        /// 批量订单改价(单个或多个操作 卖出退点+1 或卖出RMB*95折)
        /// </summary>
        /// <param name="reviseOrdersParam"></param>
        /// <returns></returns>
        public static string ReviseOrders<Order>(string reviseOrdersParam) where Order : BaseEntity
        {
            var logParam = reviseOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(reviseOrdersParam);
            string tttagKey = CommonUrl.getURL(param, reviseOrdersParam, "批量订单改价");
            //OrderIDs（必传）、SalesExchangerate(默认值,必填)、Rebate（退点/返点法）、Discount(折扣法)(二选一)
            try
            {
                if (param.ContainsKey("OrderIDs"))
                {
                    string[] _orderIDs = param.GetString("OrderIDs").Split(',');
                    decimal _salesExchangerate = Convert.ToDecimal(param.GetString("SalesExchangerate"));//销售汇率(默认选择系统)
                    int sucessCount = 0;
                    int faildCount = 0;
                    for (int i = 0; i < _orderIDs.Length; i++)
                    {
                        try
                        {
                            dynamic _order = YZ.GetDatabase(tttagKey).QueryForObject<Order>("Order.GetOrderByID", _orderIDs[i]);//有坑 不能用YZ.GetDatabase(tttagKey).Get<OrderInfo>()获取
                            if (_order != null)
                            {
                                //计算(退点法和折扣法)
                                //折扣法： 卖出人民币总价* 折扣值 （白彩钻都一样）
                                //退点法：白钻：重量*RAP*(当前订单退点+ 退点值)*销售汇率
                                //彩钻:卖出人民币总价*（100+退点值）    
                                //dynamic _customerInfo = YZ.GetDatabase(tttagKey).QueryForObject<C>("Customer.GetCustomerInfo", _order.CustomerID);//单个客户信息，通过CustomerID 
                                try
                                {
                                    int? _mode = param.GetInt("Mode");//1优惠退点 0优惠折扣
                                    if (_mode == 1)
                                    {
                                        if (_salesExchangerate != 0)
                                        {
                                            RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                                            //包货
                                            if (_order.CertType == "PARCEL")
                                            {
                                                _order.Rapnet = 0;//无Rapnet
                                            }
                                            else
                                            {
                                                _order.Rapnet = rap.GetPrice(_order);
                                            }
                                            #region new 反推
                                            if (param.ContainsKey("Confirmdiscount"))
                                            {
                                                decimal Confirmdiscount = Convert.ToDecimal(param.GetString("Confirmdiscount"));//退点 
                                                if (Confirmdiscount != 0)
                                                {
                                                    _order.Confirmdiscount = Confirmdiscount;
                                                    _order.ConfirmUSD = CalcPriceUSD(_order.IsFancy, Confirmdiscount, _order.Rapnet, _order.Weight, 1, _order.PriceUSD);
                                                    _order.ConfirmPrice = _order.ConfirmUSD * _salesExchangerate;
                                                    _order.SalesExchangerate = _salesExchangerate;
                                                }
                                                else
                                                {
                                                    return CommonLog.MsgErrorInfo("改价失败:退点不能为0");
                                                }
                                            }
                                            else if (param.ContainsKey("ConfirmPrice"))
                                            {
                                                decimal ConfirmPrice = Convert.ToDecimal(param.GetString("ConfirmPrice"));//RMB 
                                                if (ConfirmPrice > 0)
                                                {
                                                    _order.SalesExchangerate = _salesExchangerate;
                                                    _order.ConfirmPrice = ConfirmPrice;
                                                    _order.ConfirmUSD = _order.ConfirmPrice / _order.SalesExchangerate;
                                                    _order.Confirmdiscount = CalcWhiteReturnPoint(_order.IsFancy, _order.ConfirmUSD, _order.Rapnet, _order.Weight, 1, _order.PriceUSD);
                                                }
                                                else
                                                {
                                                    return CommonLog.MsgErrorInfo("改价失败:￥/Pcs 异常");
                                                }
                                            }
                                            else if (param.ContainsKey("ConfirmUSD"))
                                            {
                                                decimal ConfirmUSD = Convert.ToDecimal(param.GetString("ConfirmUSD"));//RMB 
                                                if (ConfirmUSD > 0)
                                                {
                                                    _order.SalesExchangerate = _salesExchangerate;
                                                    _order.ConfirmUSD = ConfirmUSD;
                                                    _order.ConfirmPrice = _order.ConfirmUSD * _order.SalesExchangerate;
                                                    _order.Confirmdiscount = CalcWhiteReturnPoint(_order.IsFancy, _order.ConfirmUSD, _order.Rapnet, _order.Weight, 1, _order.PriceUSD);
                                                }
                                                else
                                                {
                                                    return CommonLog.MsgErrorInfo("改价失败:$/Pcs 异常");
                                                }
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            return CommonLog.MsgErrorInfo("改价失败:汇率不能为0");
                                        }
                                    }
                                    else
                                    {
                                        #region 打折
                                        if (param.ContainsKey("Discount"))
                                        {
                                            decimal _discount = Convert.ToDecimal(param.GetString("Discount"));//打折法  85折输入0.85
                                            if (_salesExchangerate != 0 && _discount != 0)
                                            {
                                                //折扣法
                                                _order.ConfirmPrice = (decimal)_order.ConfirmPrice * (decimal)_discount;//白彩钻都一样
                                                _order.ConfirmUSD = _order.ConfirmPrice / _salesExchangerate;
                                                _order.SalesExchangerate = _salesExchangerate;
                                                //然后通过卖出人民币总价推算卖出退点
                                                //白钻：
                                                if (_order.IsFancy == 0)
                                                {
                                                    _order.Confirmdiscount = (((decimal)(_order.ConfirmPrice) / ((decimal)_order.Weight * (decimal)_order.Rapnet * (decimal)_salesExchangerate)) + (-1)) * 100;
                                                }
                                                else
                                                {
                                                    //彩钻，卖出退点为0
                                                    _order.Confirmdiscount = 0;
                                                }
                                            }
                                            else
                                            {
                                                return CommonLog.MsgErrorInfo("改价失败:汇率和折扣不能为0");
                                            }
                                        }
                                        else if (param.ContainsKey("Rebate"))
                                        {
                                            decimal _rebate = Convert.ToDecimal(param.GetString("Rebate"));//退点法(优先)            
                                            //退点法
                                            if (_salesExchangerate != 0 && _rebate != 0)
                                            {
                                                //为了保险，重新获取RAPNET （4C）
                                                RapnetPriceProvider rap = new RapnetPriceProvider("App_Data\\diamond_all_price.xml");
                                                //包货
                                                if (_order.CertType == "PARCEL")
                                                {
                                                    _order.Rapnet = 0;//无Rapnet
                                                }
                                                else
                                                {
                                                    _order.Rapnet = rap.GetPrice(_order);
                                                }
                                                //彩钻
                                                if (_order.IsFancy == 1)
                                                {
                                                    _order.ConfirmPrice = Math.Round((decimal)_order.ConfirmPrice * ((100 + (decimal)_rebate) / 100));
                                                    //卖出退点为0
                                                    _order.Confirmdiscount = 0;
                                                    _order.SalesExchangerate = _salesExchangerate;
                                                }
                                                else
                                                {
                                                    //白钻
                                                    //卖出退点=卖出退点+退点值
                                                    _order.Confirmdiscount = (decimal)_order.Confirmdiscount + _rebate;
                                                    _order.ConfirmPrice = Math.Round((decimal)_order.Weight * (decimal)_order.Rapnet * ((100 + (decimal)_order.Confirmdiscount) / 100) * (decimal)_salesExchangerate);
                                                    _order.ConfirmUSD = Math.Round((decimal)_order.Weight * (decimal)_order.Rapnet * ((100 + (decimal)_order.Confirmdiscount) / 100));
                                                    _order.SalesExchangerate = _salesExchangerate;
                                                }
                                            }
                                            else
                                            {
                                                return CommonLog.MsgErrorInfo("改价失败:汇率和退点不能为0");
                                            }
                                        }
                                        #endregion
                                    }
                                }
                                catch (Exception ex)
                                {
                                    GetMethodInfoAndWriteLogs(ex);
                                    CommonLog.SendMQMsg(tttagKey, "异常信息：批量订单改价1" + ex.StackTrace + "参数:" + logParam);
                                    return CommonLog.MsgErrorInfo("价格推算失败，程序错误");
                                }
                                //执行
                                using (ITransaction trans_reviseOrders = YZ.GetTransaction(tttagKey))
                                {
                                    Order order = JsonConvert.DeserializeObject<Order>(JsonConvert.SerializeObject(_order));
                                    int reviseOrdersResult = trans_reviseOrders.Edit(order);
                                    if (reviseOrdersResult > 0)
                                    {
                                        try
                                        {
                                            sucessCount++;
                                            trans_reviseOrders.CommitTransaction(); //触发入库事务 
                                        }
                                        catch (Exception)
                                        {
                                            faildCount++;
                                            trans_reviseOrders.RollBackTransaction();//回滚事务
                                            return CommonLog.MsgErrorInfo("改价失败");
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            CommonLog.SendMQMsg(tttagKey, "异常信息：批量订单改价2" + ex.StackTrace + "参数:" + logParam);
                            return CommonLog.MsgErrorInfo("改价失败:");
                        }
                    }
                    if (_orderIDs.Length == sucessCount)
                    {
                        CommonLog.SendMQMsg(tttagKey, "批量订单改价：" + reviseOrdersParam);
                        return CommonLog.MsgSuccessInfo("改价成功");
                    }
                    return CommonLog.MsgErrorInfo("改价失败");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("改价失败,参数错误");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：批量订单改价3" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("改价：程序错误");
            }
        }

        /// <summary>
        /// 计算退点
        /// </summary>
        /// <param name="ConfirmUSD">美元单粒价</param>
        /// <param name="Rapnet">Rapnet</param>
        /// <param name="Weight">Weight</param>
        /// <param name="Discounts">Discounts</param>
        /// <param name="SourceDolarPerGrain">原单粒价</param>
        /// <returns></returns>
        public static decimal? CalcWhiteReturnPoint(int IsFancy, decimal? ConfirmUSD, decimal? Rapnet, decimal? Weight, decimal? Discounts, decimal? SourceDolarPerGrain)
        {
            decimal? ReturnPoint = 0;
            if (IsFancy != 1)
            {
                //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                ReturnPoint = ConfirmUSD / Weight * 100 / Rapnet - 100;
            }
            else
            {
                //美元单粒价 		= 原单粒价 * (100 + 退点) / 100   
                ReturnPoint = ConfirmUSD * 100 / SourceDolarPerGrain - 100;
            }
            return ReturnPoint;
        }
        /// <summary>
        /// 已知退点反推卖价
        /// </summary>
        /// <param name="IsFancy">是否彩钻1</param>
        /// <param name="ReturnPoint">退点</param>
        /// <param name="Rapnet"></param>
        /// <param name="Weight">重量</param>
        /// <param name="Discounts">客户的优惠</param>
        /// <param name="SourceDolarPerGrain">彩钻的原单粒价</param>
        /// <returns></returns>
        public static decimal? CalcPriceUSD(int IsFancy, decimal? ReturnPoint, decimal? Rapnet, decimal? Weight, decimal? Discounts, decimal? SourceDolarPerGrain)
        {
            decimal? price = 0;
            if (IsFancy != 1)
            {
                //美元单粒价 		= RAPNET * (100 + 相应退点) / 100 * 重量
                price = Rapnet * (100 + ReturnPoint) / 100 * Weight / Discounts;
            }
            else
            {
                //美元单粒价 		= 原单粒价 * (100 + 退点) / 100   
                price = SourceDolarPerGrain * (100 + ReturnPoint) / 100 / Discounts;
            }
            return price;
        }


        /// <summary>
        /// 入库订单（处理（2采购成功，待入库）的订单到 (3入库成功，待出库)） --含事务   （改变订单状态 从2到3）
        /// </summary>
        /// <param name="arrivalOrdersParam"></param>
        /// <returns></returns>
        public static string ArrivalOrders<OrderInfo, Customer>(string arrivalOrdersParam)
            where Customer : BaseEntity, new()
            where OrderInfo : BaseEntity
        {
            var logParam = arrivalOrdersParam;
            HashParam param = Json.Deserialize<HashParam>(arrivalOrdersParam); //解析Android传过来的Json
            string tttagKey = CommonUrl.getURL(param, arrivalOrdersParam, "确认到货");
            //OrderIDs(必填) 、ArrivalTime(必传)
            try
            {
                string[] _orderIDs = param.GetString("OrderIDs").Split(',');//59,55
                if (_orderIDs.Length > 0)
                {
                    using (ITransaction trans_arrivalOrders = YZ.GetTransaction(tttagKey))
                    {
                        Dictionary<string, string> dic = new Dictionary<string, string>();
                        for (int i = 0; i < _orderIDs.Length; i++)
                        {
                            dynamic _order = new
                            {
                                OrderID = Convert.ToInt32(_orderIDs[i]),
                                Arrival = 1,
                                OrderStatus = 3,
                                ArrivalTime = param.GetString("ArrivalTime") //零售没有到货时间
                            };
                            OrderInfo orderInfo = JsonConvert.DeserializeObject<OrderInfo>(JsonConvert.SerializeObject(_order));
                            //_order.OrderID = Convert.ToInt32(_orderIDs[i]);//订单ID（OrderID）
                            //_order.Arrival = 1;//入库(0 待入库 1 已入库)
                            //_order.OrderStatus = 3;//3 待出货        
                            //_order.ArrivalTime = param.GetString("ArrivalTime");//入库时间
                            int arrivalOrdersResult = trans_arrivalOrders.Edit(orderInfo);
                            if (arrivalOrdersResult > 0)
                            {
                                HashParam hsp = new HashParam();
                                hsp.Add("OrderID", _order.OrderID);
                                int CustomerId = YZ.GetDatabase(tttagKey).QueryForObject<int>("Order.SelectOrderByOrderID", hsp);
                                //OrderInfo orderInfo = YZ.GetDatabase(tttagKey).Get<OrderInfo>((int)_order.OrderID);
                                //到货提醒 短信通知
                                dynamic _customerInfo = YZ.GetDatabase(tttagKey).Get<Customer>(CustomerId);
                                if (_customerInfo != null && !string.IsNullOrEmpty(_customerInfo.Mobile)) //客户
                                {
                                    if (!dic.ContainsKey(_customerInfo.Mobile))
                                        dic.Add(_customerInfo.Mobile, _customerInfo.UserName);
                                }
                            }
                            else
                            {
                                //跳出
                                return CommonLog.MsgErrorInfo("确认到货失败,订单不存在");
                            }
                        }
                        try
                        {
                            trans_arrivalOrders.CommitTransaction(); //提交
                            #region 消息提醒
                            foreach (string key in dic.Keys)
                            {
                                HashParam _param = new HashParam();
                                _param.Add("salesname", getSmsName(dic[key]));
                                _param.Add("supplier", tttagKey);
                                SMSManager.SendSms(key, SMSLib.SMSArrivalOrders, _param);
                            }
                            #endregion
                            CommonLog.SendMQMsg(tttagKey, "确认到货成功：" + arrivalOrdersParam);
                            return CommonLog.MsgSuccessInfo("确认到货成功");
                        }
                        catch (Exception ex)
                        {
                            GetMethodInfoAndWriteLogs(ex);
                            CommonLog.SendMQMsg(tttagKey, "异常信息：确认到货1" + ex.StackTrace + "参数:" + logParam);
                            trans_arrivalOrders.RollBackTransaction();//回滚
                            return CommonLog.MsgErrorInfo("确认到货失败,请尝试重试");
                        }
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("确认到货失败,请先选择订单");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：确认到货2" + ex.StackTrace + "参数:" + logParam);
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }

        public static string getSmsName(string name)
        {
            return name.Substring(0, name.Length >= 20 ? 20 : name.Length);
        }
        //分配异步处理的一级订单，
        public static string SubmitOthersOrder(OtherSystemLoginInfo item)
        {
            string result = string.Empty;
            try
            {
                //lock (item)
                {
                    //登录 
                    var lPostJson = new { Name = item.UserName, Pwd = item.Password };
                    var requestResult = MyHttpRequest.HttpRequest(item.Url + "/Customer/CustomerLogin", JsonConvert.SerializeObject(lPostJson));
                    requestResult = requestResult.Substring(1, requestResult.Length - 2);
                    ALogger(string.Format("SubmitOthersOrder CustomerLogin result:{0}", requestResult));
                    //登录成功则继续  // //  Customer/SubmitOrder  {"CustomerID":1,"OrderType":1,"InventoryIDs":"12595196,12595331","Remarks":"aa"}
                    int customerId = 0;
                    try
                    {
                        requestResult = requestResult.Replace("\\", "");
                        ResultInfo param1 = JsonConvert.DeserializeObject<ResultInfo>(requestResult);
                        if (param1 != null && param1.data != null)
                        {
                            customerId = param1.data.CustomerID;
                        }
                    }
                    catch (Exception ex)
                    {
                        CommonLog.SendMQMsg((item == null ? "" : item.SupplierCode), "=====>:" + JsonConvert.SerializeObject(item) + ex.StackTrace);
                        throw;
                    }
                    if (customerId > 0)
                    {
                        var sPostJson = JsonConvert.SerializeObject(new { CustomerID = customerId, OrderType = 1, InventoryIDs = item.InventoryIDs, Remarks = item.Remarks });

                        //{"msgcode":true,"msginfo":{"Successful":1,"Successful1":1,"Failed":0,"Failed1":0}}
                        requestResult = MyHttpRequest.HttpRequest(item.Url + "/Customer/SubmitOrder", sPostJson).Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}");
                        //"\"{\\\"msgcode\\\":true,\\\"msginfo\\\":{\\\"Successful\\\":1,\\\"Successful1\\\":1,\\\"Failed\\\":0,\\\"Failed1\\\":0,\\\"SuccessList\\\":[13242703]}}\""
                        if (!requestResult.Contains("SuccessList\":\"[]\"") && !requestResult.Contains("SuccessList\":null")) //SuccessList里面有数据
                        {
                            HashParam param = JsonConvert.DeserializeObject<HashParam>(requestResult);
                            //成功了需要改变对应的状态
                            if (param.GetBool("msgcode"))
                            {
                                Dictionary<string, object> param2 = JsonConvert.DeserializeObject<Dictionary<string, object>>(JsonConvert.SerializeObject(param["msginfo"]));
                                int[] sIdList = JsonConvert.DeserializeObject<int[]>(param2["SuccessList2"].ToString()); //数据中心返回
                                if (sIdList.Count() > 0)
                                {
                                    string ids = "";
                                    foreach (var id in sIdList)
                                    {
                                        ids += id.ToString()+",";
                                    }
                                    item.InventoryIDs = ids.TrimEnd(',');
                                   //var allIdList = item.OrderIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToArray(); //这里把所有的id都传过去，因为如果失败的话订单已被删除，可以不用再拿出成功的订单id
                                   result = JsonConvert.SerializeObject(item);
                                }
                                else
                                {
                                    result = "0";
                                }
                                //if (fIdList.Count() > 0) 
                                //{
                                //    //SubmitOrderErrorAndSendMsg(item);
                                //}
                            }
                            else
                            {
                                //SubmitOrderErrorAndSendMsg(item);
                                ALogger("分配异步处理的一级订单出错 SubmitOthersOrder Exception：没有返回成功的订单信息");
                                result = "0";
                            }
                        }
                        else
                        {
                            ALogger("分配异步处理的一级订单出错 SubmitOthersOrder Exception：没有成功的订单信息");
                            result = "0";
                        }
                    }
                    else
                    {
                        ALogger("分配异步处理的一级订单出错 SubmitOthersOrder Exception：没有客户信息");
                        result = "0";
                    }
                }
            }
            catch (Exception ee)
            {
                ALogger(string.Format("分配异步处理的一级订单出错 SubmitOthersOrder Exception:{0}", ee.StackTrace));
                result = "-1";
            }
            return result;
        }
        //分配异步处理的一级订单，
        /// <summary>
        /// 
        /// </summary>
        /// <param name="otherSystemLoginInfos">非现货供应商的登录信息，包含需要下单的URL，下单账号等</param>
        /// <param name="dict">对应供应商需要下单的ids</param>
        /// <returns></returns>
        public static IList<OtherSystemLoginInfo> SubmitOthersOrderByPre(IList<OtherSystemLoginInfo> otherSystemLoginInfos, Dictionary<string, string> dict)
        {
            string tagkey = "";
            List<OtherSystemLoginInfo> list = new List<OtherSystemLoginInfo>();
            try
            {
                foreach (var otherSystemLoginInfo in otherSystemLoginInfos)
                {
                    tagkey = otherSystemLoginInfo.SupplierCode;
                    if (dict.ContainsKey(otherSystemLoginInfo.SupplierCode))
                    {
                        CommonLog.SendMQMsg(otherSystemLoginInfo.SupplierCode, "提交二级订单IDs:" + dict[otherSystemLoginInfo.SupplierCode]);
                        otherSystemLoginInfo.InventoryIDs = dict[otherSystemLoginInfo.SupplierCode];
                        var result = SubmitOthersOrder(otherSystemLoginInfo);
                        CommonLog.SendMQMsg(otherSystemLoginInfo.SupplierCode, "返回提交二级订单结果:" + result);
                        if (result != "0" && result != "1")
                        {
                            OtherSystemLoginInfo info = JsonConvert.DeserializeObject<OtherSystemLoginInfo>(result);
                            list.Add(info);
                        }
                    }
                    else
                    {
                        CommonLog.SendMQMsg(otherSystemLoginInfo.SupplierCode, "供应商+客户名2");
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                CommonLog.SendMQMsg(tagkey, "返回提交二级订单结果异常=====>:" + ex.StackTrace);
            }
            return list;
        }


        #endregion 订单

        /// <summary> 
        //失败了则发送信息给对应业务
        /// </summary>
        /// <param name="item"></param>
        public static void SubmitOrderErrorAndSendMsg(OtherSystemLoginInfo item)
        {
            if (IsPhoneNo(item.tel))
            {
                HashParam hsParam2 = new HashParam();
                hsParam2["name"] = item.name;
                hsParam2["supplier"] = item.SupplierCode;
                hsParam2["sn"] = item.SNs;
                SMSManager.SendSms(item.tel, SMSLib.SMSSubmitOrderError, hsParam2); //客户
            }
        }
        #region 正则验证手机号码
        public static bool IsPhoneNo(string str_PhoneNo)
        {
            if (!string.IsNullOrEmpty(str_PhoneNo))
                return System.Text.RegularExpressions.Regex.IsMatch(str_PhoneNo, @"^[1]+\d{10}");
            return false;
        }
        public static void ALogger(string message)
        {
            Logger.Error(typeof(AllPublic), message);

        }
        #endregion


        #region  格式化相关
        //形状格式化
        public static string ShapeFormat(int shapeValue)
        {
            if (shapeValue == 1)
            {
                return "圆形";
            }
            else if (shapeValue == 2)
            {
                return "公主方";
            }
            else if (shapeValue == 3)
            {
                return "长祖母绿";
            }
            else if (shapeValue == 4)
            {
                return "长雷迪恩";
            }
            else if (shapeValue == 5)
            {
                return "椭圆形";
            }
            else if (shapeValue == 6)
            {
                return "梨形";
            }
            else if (shapeValue == 7)
            {
                return "马眼形";
            }
            else if (shapeValue == 8)
            {
                return "心形";
            }
            else if (shapeValue == 9)
            {
                return "三角形";
            }
            else if (shapeValue == 10)
            {
                return "垫形";
            }
            else if (shapeValue == 11)
            {
                return "其他";
            }
            else if (shapeValue == 17)
            {
                return "方祖母绿";
            }
            else if (shapeValue == 18)
            {
                return "方雷迪恩";
            }
            else
            {
                return "" + shapeValue;
            }
        }
        //形状格式化
        public static int GetShape(string shapeValue)
        {
            if (shapeValue == "圆形")
            {
                return 1;
            }
            else if (shapeValue == "公主方")
            {
                return 2;
            }
            else if (shapeValue == "长祖母绿")
            {
                return 3;
            }
            else if (shapeValue == "长雷迪恩")
            {
                return 4;
            }
            else if (shapeValue == "椭圆形")
            {
                return 5;
            }
            else if (shapeValue == "梨形")
            {
                return 6;
            }
            else if (shapeValue == "马眼形")
            {
                return 7;
            }
            else if (shapeValue == "心形")
            {
                return 8;
            }
            else if (shapeValue == "三角形")
            {
                return 9;
            }
            else if (shapeValue == "垫形")
            {
                return 10;
            }
            else if (shapeValue == "其他")
            {
                return 11;
            }
            else if (shapeValue == "方祖母绿")
            {
                return 17;
            }
            else if (shapeValue == "方雷迪恩")
            {
                return 18;
            }
            else
            {
                return 0;
            }
        }
        //订单类型格式化
        public static string OrderTypeFormat(int? orderTypeValue)
        {
            if (orderTypeValue == 1)
            {
                return "客主";
            }
            else if (orderTypeValue == 2)
            {
                return "代客";
            }
            else if (orderTypeValue == 3)
            {
                return "录入";
            }
            else if (orderTypeValue == 4)
            {
                return "二级";
            }
            else
            {
                return "" + orderTypeValue;
            }
        }
        //订单状态格式化(团队)
        public static string OrderStatusFormat(int? orderStatusValue)
        {
            if (orderStatusValue == 1)
            {
                return "待采购";
            }
            else if (orderStatusValue == 2)
            {
                return "待到货";
            }
            else if (orderStatusValue == 3)
            {
                return "待出货";
            }
            else if (orderStatusValue == 4)
            {
                return "已出货";
            }
            else if (orderStatusValue == 5)
            {
                return "已作废";
            }
            else if (orderStatusValue == 6)
            {
                return "已自留";
            }
            else if (orderStatusValue == 7)
            {
                return "已退回";
            }
            else
            {
                return "" + orderStatusValue;
            }
        }
        //订单状态格式化(客户)
        public static string CustomerOrderStatusFormat(int? orderStatusValue)
        {
            if (orderStatusValue == 1)
            {
                return "下单成功";
            }
            else if (orderStatusValue == 2)
            {
                return "定购成功";
            }
            else if (orderStatusValue == 3)
            {
                return "到货成功";
            }
            else if (orderStatusValue == 4)
            {
                return "交货成功";
            }
            else if (orderStatusValue == 5)
            {
                return "作废成功";
            }
            else if (orderStatusValue == 6)
            {
                return "退货成功";
            }
            else if (orderStatusValue == 7)
            {
                return "退货成功";
            }
            else
            {
                return "" + orderStatusValue;
            }
        }
        /// 付款状态格式化
        public static string ReceiptStatusFormat(int? paymentstatusValue)
        {
            if (paymentstatusValue == 0)
            {
                return "未付";
            }
            else if (paymentstatusValue == 1)
            {
                return "已付";
            }
            else
            {
                return "" + paymentstatusValue;
            }
        }
        //收款状态格式化
        public static string PaymentStatusFormat(int? paymentstatusValue)
        {
            if (paymentstatusValue == 0)
            {
                return "未收";
            }
            else if (paymentstatusValue == 1)
            {
                return "已收";
            }
            else
            {
                return "" + paymentstatusValue;
            }
        }
        //账户格式化 12-3
        public static string PaymentModelFormat(string paymentModelValue)
        {
            if (paymentModelValue == "1")
            {
                return "支付宝";
            }
            else if (paymentModelValue == "2")
            {
                return "微信";
            }
            else if (paymentModelValue == "3")
            {
                return "中行";
            }
            else if (paymentModelValue == "4")
            {
                return "农行";
            }
            else if (paymentModelValue == "5")
            {
                return "工行";
            }
            else if (paymentModelValue == "6")
            {
                return "建行";
            }
            else if (paymentModelValue == "7")
            {
                return "民生";
            }
            else if (paymentModelValue == "8")
            {
                return "平安";
            }
            else if (paymentModelValue == "9")
            {
                return "优惠额";
            }
            else if (paymentModelValue == "10")
            {
                return "手续费";
            }
            else if (paymentModelValue == "11")
            {
                return "现金";
            }
            else
            {
                return paymentModelValue;
            }
        }
        //充值类型格式化 12-3
        public static string OperationModelFormat(int? operationModelValue)
        {
            if (operationModelValue == 1)
            {
                return "已充值";
            }
            else if (operationModelValue == 0)
            {
                return "待充值";
            }
            else if (operationModelValue == -1)
            {
                return "已作废";
            }
            else
            {
                return "待查 " + operationModelValue;
            }
        }
        //交易类型Type 12-10
        public static string TypeFormat(int? typeValue)
        {
            if (typeValue == 1)
            {
                return "收入";
            }
            else if (typeValue == 3)
            {
                return "定金";
            }
            else if (typeValue == 2)
            {
                return "支出";
            }
            else if (typeValue == 4)
            {
                return "提现";
            }
            else
            {
                return "" + typeValue;
            }
        }
        //账户类型Account
        public static string AccountFormat(int? accountValue)
        {
            if (accountValue == 1)
            {
                return "工商";
            }
            else if (accountValue == 2)
            {
                return "建设";
            }
            else if (accountValue == 3)
            {
                return "中行";
            }
            else if (accountValue == 4)
            {
                return "农业";
            }
            else if (accountValue == 5)
            {
                return "支付宝";
            }
            else if (accountValue == 6)
            {
                return "微信";
            }
            else if (accountValue == 7)
            {
                return "HK-$";
            }
            else if (accountValue == 8)
            {
                return "现金";
            }
            else
            {
                return "" + accountValue;
            }
        }
        //流水状态Status
        public static string StatusFormat(int? statusValue)
        {
            if (statusValue == 1)
            {
                return "已审核";
            }
            else if (statusValue == 0)
            {
                return "待审核";
            }
            else if (statusValue == -1)
            {
                return "已作废";
            }
            else
            {
                return "" + statusValue;
            }
        }
        #region 裸钻状态
        public static string GetStatus(int status)
        {
            string result = string.Empty;
            switch (status)
            {
                case 1:
                    result = "在库";
                    break;
                case 2:
                    result = "借出";
                    break;
                case 3:
                    result = "实验室";
                    break;
                case 4:
                    result = "保留";
                    break;
                case 5:
                    result = "展会";
                    break;
                case 6:
                    result = "报关中";
                    break;
                default:
                    result = "其他";
                    break;
            }
            return result;
        }
        #endregion
        public static string ConventTime(DateTime? times)
        {
            return (times != null ? Convert.ToDateTime(times).ToString("yyyy-MM-dd").Replace("0001-01-01", "-") : "");
        }
        #endregion


        /// <summary>
        /// 转换方法：Json
        /// </summary>
        /// <param name="param"></param>
        /// <param name="methodLib"></param>
        /// <returns></returns>
        public static string ConvertAndFormatToJSONByOpenInterface<T>(T param)
        {
            string[] IgnoreParams = new string[] { "HDImage", "HAImage", "SupplierReturn", "Tag", "DiamondNumber", "CustomerId","PurchaseDiscountReturn","PurchaseUSDPerCarat",
                                                      "SourceDiscountReturn", "DiscountReturn", "SourceDolarPerGrain","SourceDolarPerCarat", "DolarPerGrain","DolarPerCarat" ,"RMBPerGrain","RMBPerCarat","CustomerRMBPerCarat",
                                                    "UserID","ImportTransNo","SysStatus","USDPerCarat","USDPerGrain","HDImageUrl","H3DImageUrl","SuppliersBuyRMB","SuppliersProvider","ShipTime","TotalCount","PageSize","PageIndex","PageCount","Stock"};
            //解析参数
            string requestJson = JsonConvert.SerializeObject(
                    param,
                    Newtonsoft.Json.Formatting.Indented,
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver = new DynamicContractResolver(IgnoreParams)
                    }
                 );
            return requestJson;
        }

        /// <summary>
        /// 导出上传模板
        /// </summary>
        /// <returns></returns>
        public static string DownTemplate(string param)
        {
            //string FileName = "upload_template.xlsx";//文件名
            string FileName = "upload_template.xls";//文件名
            try
            {
                //判断文件夹是否存在
                if (Directory.Exists(HttpContext.Current.Server.MapPath("/excel/")))
                {
                    //判断文件是否存在
                    if (File.Exists(HttpContext.Current.Server.MapPath("/excel/") + FileName))
                    {
                        //返回文件下载地址 http://localhost:3952/excel/xx.xls
                        return CommonLog.MsgSuccessInfo(HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + "/excel/" + FileName);//返回文件下载地址 http://localhost:3952/excel/xx.xls
                    }
                    else
                    {
                        return CommonLog.MsgErrorInfo("下载失败，文件不存在");
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("下载失败，文件夹不存在");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg("异常信息：导出上传模板", ex.StackTrace);
                return CommonLog.MsgErrorInfo("下载失败:");
            }
        }
        public static string ReturnDate(string date)
        {
            return !string.IsNullOrEmpty(date) ? Convert.ToDateTime(date).ToString("yyyy-MM-dd") : "";
        }

        /// <summary>
        /// 供应商缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string[] CachePriorities(string key)
        {
            if (HttpRuntime.Cache.Get("Priorities" + key) == null)
            {
                //get string[] 
                string[] strArray = GetSupplierCodeList(key);
                HttpRuntime.Cache.Insert("Priorities" + key, strArray, null, DateTime.Now.AddSeconds(GlobalConfig.ExpirationTimeOut), TimeSpan.Zero);
                return strArray;
            }
            else
                return HttpRuntime.Cache.Get("Priorities" + key) as string[];
        }
        //得到所有现货供应商 8-26
        public static string[] GetSupplierCodeList(string key)
        {
            IList<HashResult> list = YZ.GetDatabase(key).QueryForList<HashResult>("Supplier.GetSupplierCodeList", null);
            string[] codes = new string[list.Count];
            for (int i = 0; i < list.Count; i++)
            {
                codes[i] = list[i]["SupplierCode"].ToString();
            }
            return codes;
        }

        /// <summary>
        /// 返回更新日志 9-29
        /// </summary>
        /// <returns></returns>
        public static string UpdateLog(string param)
        {
            var logParam = param;
            //templateJSON
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(AppDomain.CurrentDomain.BaseDirectory + "\\update_log.xml");//加载xml
                return doc.InnerXml;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("读取失败");
            }
        }

        /// <summary>
        /// 单个订单
        /// </summary>
        /// <param name="orderInfoParam"></param>
        /// <returns></returns>
        public static string GetRingOrderInfo<OrderInfo>(string orderInfoParam)
        {
            var logParam = orderInfoParam;
            HashParam param = Json.Deserialize<HashParam>(orderInfoParam);
            string tttagKey = CommonUrl.getURL(param, orderInfoParam);
            //templateJSON
            try
            {
                OrderInfo order = YZ.GetDatabase(tttagKey).QueryForObject<OrderInfo>("Order.GetOrderByID", param.GetInt("OrderID"));
                if (order != null)
                {
                    return CommonLog.MsgSuccessObj(JsonConvert.SerializeObject(order));//Serialize 序列化
                }
                else
                {
                    return CommonLog.MsgErrorInfo("获取订单失败，请检查订单标识");
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("内部错误");
            }
        }
        /// <summary>
        /// 更新订单
        /// </summary>
        /// <param name="selectParam"></param>
        /// <returns></returns>
        public static string UpdateProductsOrder(string strParam)
        {
            var logParam = strParam;
            string tttagKey = CommonUrl.getURL(null, strParam);
            Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(strParam));
            if (param.ContainsKey("IsCreateShip"))
            {
                param.Add("ShipNo", DateTime.Now.ToString("MMddHHmmss"));//出货单号MMddHHmmss
                param.Remove("IsCreateShip");
            }
            var i = YZ.GetDatabase(tttagKey).Update("Order.UpdateProductsOrderStatus", param);
            if (i > 0)
            {
                if (param.ContainsKey("OrderStatus"))
                {
                    if (param["OrderStatus"].ToString() == "2")
                        return CommonLog.MsgSuccessInfo("采购成功");
                    else if (param["OrderStatus"].ToString() == "3")
                        return CommonLog.MsgSuccessInfo("到货成功");
                    else if (param["OrderStatus"].ToString() == "4")
                        return CommonLog.MsgSuccessInfo("出货成功");
                    else if (param["OrderStatus"].ToString() == "5")
                        return CommonLog.MsgSuccessInfo("作废订单成功");
                    else if (param["OrderStatus"].ToString() == "6")
                        return CommonLog.MsgSuccessInfo("退货成功");
                    else if (param["OrderStatus"].ToString() == "7")
                        return CommonLog.MsgSuccessInfo("已退回");
                }
                if (param.ContainsKey("PaymentStatus"))
                {
                    return CommonLog.MsgSuccessInfo("付款成功");
                }
                if (param.ContainsKey("ReceiptStatus"))
                {
                    return CommonLog.MsgSuccessInfo("收款成功");
                }
                if (param.ContainsKey("ShipNo"))
                {
                    return CommonLog.MsgSuccessInfo("制单成功");
                }
                if (param.ContainsKey("PurchaseUserID"))
                {
                    return CommonLog.MsgSuccessInfo("更新采购成功");
                }
                if (param.ContainsKey("Online"))
                {
                    return CommonLog.MsgSuccessInfo("回库成功");
                }

                return CommonLog.MsgSuccessInfo("更新订单成功");
            }
            else
            {
                if (param.ContainsKey("OrderStatus"))
                {
                    if (param["OrderStatus"].ToString() == "2")
                        return CommonLog.MsgSuccessInfo("采购失败");
                    else if (param["OrderStatus"].ToString() == "3")
                        return CommonLog.MsgSuccessInfo("到货失败");
                    else if (param["OrderStatus"].ToString() == "4")
                        return CommonLog.MsgSuccessInfo("出货失败");
                    else if (param["OrderStatus"].ToString() == "5")
                        return CommonLog.MsgSuccessInfo("作废订单成功");
                    else if (param["OrderStatus"].ToString() == "6")
                        return CommonLog.MsgSuccessInfo("退货失败");
                    else if (param["OrderStatus"].ToString() == "7")
                        return CommonLog.MsgSuccessInfo("已退回");
                }
                if (param.ContainsKey("PaymentStatus"))
                {
                    return CommonLog.MsgSuccessInfo("付款失败");
                }
                if (param.ContainsKey("ReceiptStatus"))
                {
                    return CommonLog.MsgSuccessInfo("收款失败");
                }
                if (param.ContainsKey("ShipNo"))
                {
                    return CommonLog.MsgSuccessInfo("制单失败");
                }
                if (param.ContainsKey("PurchaseUserID"))
                {
                    return CommonLog.MsgSuccessInfo("更新采购失败");
                }
                if (param.ContainsKey("Online"))
                {
                    return CommonLog.MsgSuccessInfo("回库失败");
                }
                return CommonLog.MsgErrorInfo("更新订单失败");
            }
        }
        /// <summary>
        ///  删除购物车
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string DeleteCart(string strParam)
        {
            var logParam = strParam;
            string tttagKey = CommonUrl.getURL(null, strParam);
            Hashtable param = MyHashtable.NewHashtable(Json.Deserialize<Hashtable>(strParam));
            try
            {
                bool b = YZ.GetDatabase(tttagKey).Delete("Cart.DelCartInfoByIds", param) > 0;
                if (b)
                {
                    return CommonLog.MsgSuccessInfo("移除成功");
                }
                else
                {
                    return CommonLog.MsgErrorInfo("移除失败");
                }
            }
            catch (Exception ex)
            {
                return CommonLog.MsgErrorInfo("程序错误");
            }
        }
        #region 获取需要显示的供应商
        /// <summary>
        ///  只显示设置好的供应商
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string ReturnSupplier(string strParam)
        {
            var logParam = strParam;
            try
            {
                HashParam hsParam = Json.Deserialize<HashParam>(strParam);
                string tttagKey = CommonUrl.getURL(hsParam, strParam);
                string productName = "";
                int goodType = 0;
                if (!hsParam.ContainsKey("GoodsType"))
                {
                    return CommonLog.MsgErrorInfo("未指定类别");
                }
                else
                {
                    goodType = hsParam.GetInt("GoodsType").Value;
                }
                string result = string.Empty;
                //1;裸钻2;统包3;成品4;彩宝5;翡翠6;素金 
                if (goodType == GoodsType.Diamond)
                {
                    productName = "diamond";
                }
                else if (goodType == GoodsType.Parcel)
                {
                    productName = "parcel";
                }
                else if (goodType == GoodsType.Ring)
                {
                    productName = "ring";
                }
                else if (goodType == GoodsType.Gem)
                {
                    productName = "gem";
                }
                else if (goodType == GoodsType.Emerald)
                {
                    productName = "emerald";
                }
                else if (goodType == GoodsType.PrimeGolds)
                {
                    productName = "primegolds";
                }
                else if (goodType == GoodsType.InlaySettings)
                {
                    productName = "inlaysettings";
                }
                else
                {
                    return CommonLog.MsgErrorInfo("未知的商品类别");
                }
                {
                    //从设置里取得已关的供应商
                    string whiteSupplier = MyHttpRequest.GetSupplierByCondition(tttagKey, productName);
                    WhiteSupplier whiteSupplierList = Json.Deserialize<WhiteSupplier>(whiteSupplier);
                    //从数据中心获取所有供应商
                    string allSupplier = string.Empty;
                    SupplierRow allSupplierList = null;
                    if (System.Web.HttpContext.Current.Cache.Get("Cache:InitSupplier") == null)
                    {
                        allSupplier = MyHttpRequest.GetSupplierListFromDataCenterAll(tttagKey).Replace("prime-golds", "prime_golds").Replace("inlay-settings", "inlay_settings");
                        allSupplierList = Json.Deserialize<SupplierRow>(allSupplier);
                        InitSupplier("SupplierDB", allSupplierList);
                        InitSupplierWhite(tttagKey, ref allSupplierList);
                    }
                    else
                    {
                        #region
                        //数据中心返回的供应商信息
                        SupplierRow list = System.Web.HttpContext.Current.Cache.Get("Cache:InitSupplier") as SupplierRow;
                        //过滤
                        dynamic values;
                        HashParam hParam = new HashParam();
                        if (goodType == GoodsType.Diamond)
                        {
                            hParam.Add("stocks", 1);
                            values = from s in list.rows
                                     where s.classify.stocks
                                     select s;
                        }
                        else if (goodType == GoodsType.Parcel)
                        {
                            hParam.Add("parcels", 1);
                            values = from s in list.rows
                                     where s.classify.parcels
                                     select s;
                        }
                        else if (goodType == GoodsType.Ring)
                        {
                            hParam.Add("inlays", 1);
                            values = from s in list.rows
                                     where s.classify.inlays
                                     select s;
                        }
                        else if (goodType == GoodsType.Gem)
                        {
                            hParam.Add("gems", 1);
                            values = from s in list.rows
                                     where s.classify.gems
                                     select s;
                        }
                        else if (goodType == GoodsType.Emerald)
                        {
                            hParam.Add("emeralds", 1);
                            values = from s in list.rows
                                     where s.classify.emeralds
                                     select s;
                        }
                        else if (goodType == GoodsType.PrimeGolds)
                        {
                            hParam.Add("prime_golds", 1);
                            values = from s in list.rows
                                     where s.classify.prime_golds
                                     select s;
                        }
                        else if (goodType == GoodsType.InlaySettings)
                        {
                            hParam.Add("inlay_settings", 1);
                            values = from s in list.rows
                                     where s.classify.inlay_settings
                                     select s;
                        }
                        else
                        {
                            values = "";
                        }
                        allSupplier = "{\"rows\": " + JsonConvert.SerializeObject(values) + "}";
                        allSupplierList = Json.Deserialize<SupplierRow>(allSupplier);
                        InitSupplierWhite(tttagKey, ref allSupplierList);
                        GetSupplierWhite(tttagKey, allSupplierList, hParam); 
                        #endregion
                    }
                    if (whiteSupplierList == null || whiteSupplierList.result == false)
                    {
                        if (allSupplierList.rows.Count() == 0)
                            return allSupplier;
                        else
                            return JsonConvert.SerializeObject(allSupplierList) ;
                    }
                    //只显示白名单 whiteSupplierList  allSupplierList 交集
                    var names = whiteSupplierList.msg.ToList().Select(p => p.name.ToUpper()).ToList();
                    if (names.Contains(tttagKey))
                    {
                        names.Remove(tttagKey);
                    }
                    //白名单
                    var resultSupplier = from all in allSupplierList.rows
                                         where (
                                            (from exceptSupplier in allSupplierList.rows
                                             select exceptSupplier.supplier.ToUpper()).Except(names)
                                         ).Contains(all.supplier.ToUpper())
                                         select all;
                    string aa = JsonConvert.SerializeObject(resultSupplier).Replace("prime_golds", "prime-golds").Replace("inlay_settings", "inlay-settings");
                    string result1 = "{\"rows\": " + aa + "}";
                    return result1;
                }
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                throw;
            }
            return "";
        }

        public static void InitSupplierWhiteSet(string tttagKey)
        {
            string allSupplier = MyHttpRequest.GetSupplierListFromDataCenter(tttagKey).Replace("prime-golds", "prime_golds").Replace("inlay-settings", "inlay_settings");
            SupplierRow allSupplierList = Json.Deserialize<SupplierRow>(allSupplier);
            InitSupplier("SupplierDB", allSupplierList);
            YZ.GetDatabase(tttagKey).QueryForObject("SupplierWhite.TruncateSupplier", null);
            InitSupplierWhite(tttagKey, ref allSupplierList);
            Thread.Sleep(2000);
        }
        public static void GetAllSupplier(string tttagKey)
        {
            string allSupplier = MyHttpRequest.GetSupplierListFromDataCenter(tttagKey).Replace("prime-golds", "prime_golds").Replace("inlay-settings", "inlay_settings");
            SupplierRow allSupplierList = Json.Deserialize<SupplierRow>(allSupplier);
            InitSupplier("SupplierDB", allSupplierList); 
        }
        #region 初始化供应商
        /// <summary>
        /// 初始化供应商
        /// </summary>
        /// <param name="tttagKey"></param>
        /// <param name="allSupplierList"></param>
        public static void InitSupplier(string tttagKey, SupplierRow allSupplierList)
        {
            YZ.GetDatabase(tttagKey).QueryForObject("SupplierListFromDataCenter.TruncateSupplier", null);
            if (allSupplierList.rows.Count() > 0)
            {
                List<object> listSupplier = new List<object>();
                foreach (var item in allSupplierList.rows)
                {
                    SupplierListFromDataCenter supplier = new SupplierListFromDataCenter();
                    supplier.Supplier_Name = item.supplier;
                    supplier.Supplier_Short_Name = item.short_name;
                    supplier.Supplier_Full_Name = item.full_name;
                    supplier.stocks = item.classify.stocks ? 1 : 0;
                    supplier.parcels = item.classify.parcels ? 1 : 0;
                    supplier.inlays = item.classify.inlays ? 1 : 0;
                    supplier.emeralds = item.classify.emeralds ? 1 : 0;
                    supplier.gems = item.classify.gems ? 1 : 0;
                    supplier.prime_golds = item.classify.prime_golds ? 1 : 0;
                    supplier.inlay_settings = item.classify.inlay_settings ? 1 : 0;
                    listSupplier.Add(supplier); 
                }
                if (listSupplier.Count > 0)
                    YZ.GetDatabase(tttagKey).Add(listSupplier);

                ///缓存 数据中心返回的供应商信息
                System.Web.HttpContext.Current.Cache.Remove("Cache:InitSupplier");
                System.Web.HttpContext.Current.Cache.Insert("Cache:InitSupplier", allSupplierList, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
            }
        }

        /// <summary>
        /// 初始化白名单
        /// </summary>
        /// <param name="tttagKey"></param>
        /// <param name="allSupplierList"></param>
        public static void InitSupplierWhite(string tttagKey, ref SupplierRow allSupplierList)
        {
            IList<SupplierWhite> list = YZ.GetDatabase(tttagKey).QueryForList<SupplierWhite>("SupplierWhite.GetList", null);
            if (list.Count == 0)
            {
                if (allSupplierList.rows.Count() > 0)
                {
                    List<object> listSupplier = new List<object>();
                    foreach (var item in allSupplierList.rows)
                    {
                        if (item.whitelist != null)
                        {
                            if (item.whitelist.stocks || item.whitelist.parcels || item.whitelist.inlays || item.whitelist.emeralds ||
                                item.whitelist.gems || item.whitelist.prime_golds || item.whitelist.inlay_settings)
                            {
                                SupplierWhite supplier = new SupplierWhite();
                                supplier.Supplier_Name = item.supplier;
                                supplier.Supplier_Short_Name = item.short_name;
                                supplier.Supplier_Full_Name = item.full_name;
                                supplier.stocks = item.whitelist.stocks ? 1 : 0;
                                supplier.parcels = item.whitelist.parcels ? 1 : 0;
                                supplier.inlays = item.whitelist.inlays ? 1 : 0;
                                supplier.emeralds = item.whitelist.emeralds ? 1 : 0;
                                supplier.gems = item.whitelist.gems ? 1 : 0;
                                supplier.prime_golds = item.whitelist.prime_golds ? 1 : 0;
                                supplier.inlay_settings = item.whitelist.inlay_settings ? 1 : 0;
                                listSupplier.Add(supplier);
                            }
                        }
                        else
                        {
                            SupplierDataSet set = new SupplierDataSet();
                            set.stocks = false;
                            set.parcels = false;
                            set.inlays = false;
                            set.emeralds = false;
                            set.gems = false;
                            set.prime_golds = false;
                            set.inlay_settings = false;
                            item.whitelist = set;
                        } 
                    }
                    if (listSupplier.Count > 0)
                        YZ.GetDatabase(tttagKey).Add(listSupplier);
                }
            }
            else
            {
                if (allSupplierList.rows.Count() > 0)
                {
                    foreach (var item in allSupplierList.rows)
                    {
                        SupplierWhite white = (from w in list
                                               where w.Supplier_Name.Equals(item.supplier)
                                               select w).FirstOrDefault();
                        SupplierDataSet set = new SupplierDataSet();
                        if (white != null)
                        {

                            set.stocks = white.stocks == 1 ? true : false;
                            set.parcels = white.parcels == 1 ? true : false;
                            set.inlays = white.inlays == 1 ? true : false;
                            set.emeralds = white.emeralds == 1 ? true : false;
                            set.gems = white.gems == 1 ? true : false;
                            set.prime_golds = white.prime_golds == 1 ? true : false;
                            set.inlay_settings = white.inlay_settings == 1 ? true : false;
                        }
                        else
                        {
                            set.stocks =   false;
                            set.parcels =   false;
                            set.inlays =   false;
                            set.emeralds =  false;
                            set.gems =   false;
                            set.prime_golds =   false;
                            set.inlay_settings =  false;
                        }
                        item.whitelist = set;
                    }
                }
            }
        }
        /// <summary>
        /// 获取白名单
        /// </summary>
        /// <param name="tttagKey"></param>
        /// <param name="allSupplierList"></param>
        /// <param name="hsParam"></param>
        /// <returns></returns>
        public static SupplierRow GetSupplierWhite(string tttagKey, SupplierRow allSupplierList, HashParam hsParam)
        {
            IList<SupplierWhite> list = YZ.GetDatabase(tttagKey).QueryForList<SupplierWhite>("SupplierWhite.GetList", null);

            foreach (var item in allSupplierList.rows)
            {
                foreach (var v in list)
                {
                    if (v.Supplier_Name == item.supplier)
                    {
                        if (hsParam.ContainsKey("stocks"))
                        {
                            item.whitelist.stocks = v.stocks == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("parcels"))
                        {
                            item.whitelist.parcels = v.parcels == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("inlays"))
                        {
                            item.whitelist.inlays = v.inlays == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("emeralds"))
                        {
                            item.whitelist.emeralds = v.emeralds == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("gems"))
                        {
                            item.whitelist.gems = v.gems == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("prime_golds"))
                        {
                            item.whitelist.prime_golds = v.prime_golds == 1 ? true : false; 
                        }
                        else if (hsParam.ContainsKey("inlay_settings"))
                        {
                            item.whitelist.inlay_settings = v.inlay_settings == 1 ? true : false; 
                        }
                    }
                }

            }
            return allSupplierList;
        }
        #endregion
        /// <summary>
        /// 获取原数据库中已开供应商的名称
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetSupplierName(int SupplierType, string key)
        {
            string name = "";
            try
            {
                HashParam hparam = new HashParam();
                hparam.Add("SupplierType", SupplierType);
                IList<SupplierInfo> list = YZ.GetDatabase(key).QueryForList<SupplierInfo>("Supplier.GetList", hparam);
                if (list != null && list.Count > 0)
                {
                    foreach (SupplierInfo si in list)
                    {
                        name += si.SupplierCode.ToUpper() + ",";
                    }
                }
                return name.TrimEnd(',');
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return "";
            }
        }
        #endregion


        #region 获取用户日志  和 备注
        /// <summary>
        ///  获取用户查询次数
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string GetSearchCount(string strParam)
        {
            var logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            hsParam.Add("tagKey", tttagKey);
            Yunzuan.Common.ServiceReference1.MessageServiceClient mc = new Yunzuan.Common.ServiceReference1.MessageServiceClient();
            return mc.GetSearchCount(JsonConvert.SerializeObject(hsParam));
        }
        /// <summary>
        /// 获取用户查询明细
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string GetSearchCountDetail(string strParam)
        {
            var logParam = strParam;
            HashParam hsParam = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(hsParam, strParam);
            hsParam.Add("tagKey", tttagKey);
            Yunzuan.Common.ServiceReference1.MessageServiceClient mc = new Yunzuan.Common.ServiceReference1.MessageServiceClient();
            return mc.GetSearchCountDetail(JsonConvert.SerializeObject(hsParam));
        }
        #endregion


        #region 产品公用模块
        /// <summary>
        /// 产品公用模块（包含成品，统包，彩宝等）
        /// </summary>
        /// <param name="getInlaysParam">当前产品对应参数</param>
        /// <param name="requestUrl">产品请求URL</param>
        /// <returns></returns>
        public static string AllProduct(string getProductParam, string key, string requestUrl, string method = "post", bool isOriginalJson = false)
        {
            string tttagKey = key;
            method = method.ToLower();
            var msgInfo1 = "{\"msgcode\":#code,\"msginfo\":\"#msg\"}";
            try
            {
                MyHttpRequest.RequestLib lib = new MyHttpRequest.RequestLib();
                switch (method)
                {
                    case "delete":
                        lib = MyHttpRequest.RequestLib.DELETE;
                        break;
                    case "put":
                        lib = MyHttpRequest.RequestLib.PUT;
                        break;
                    case "get":
                        lib = MyHttpRequest.RequestLib.GET;
                        break;
                    default:  //POST
                        lib = MyHttpRequest.RequestLib.POST;
                        break;
                }
                var responseJson = MyHttpClient.GetRsultFromDataCenterNew(tttagKey, requestUrl, getProductParam, 2, null, lib);
                //MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, lib);
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：产品公用模块（包含成品，统包，彩宝等）" + ex.StackTrace);
                return string.Format(msgInfo1, "false", "程序错误");
            }
        }
        //通过cartinfolist得到参数ids
        public static string GetIdsStrParamByIds(int[] xxIds)
        {
            StringBuilder sbIds = new StringBuilder();
            for (int i = 0; i < xxIds.Length; i++)
            {
                sbIds.Append("\"" + xxIds[i] + "\",");
            }
            return string.Format(" {{\"useDict\": true,\"ID\":[{0}]}}", sbIds.ToString().TrimEnd(','));
        }
        #endregion 产品公用模块

        public static string ConvertToInventoryFormat(string responseJson)
        {
            responseJson = responseJson.Replace("records", "TotalCount")
                .Replace("result", "Result")
                .Replace("OriginUSDPerGrain", "SourceDolarPerGrain")
                .Replace("OriginDiscountReturn", "SourceDiscountReturn")
                .Replace("InsertTime", "CreateTime")
                .Replace("OriginUSDPerCarat", "SourceDolarPerCarat");
            return responseJson;
        }

        #region 后台删除数据中心订单
        /// <summary>
        /// 删除订单的xx，自己人用传参数key,IDs
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns>
        public static string DelOrderFromDataCenter(string strParam)
        {
            HashParam param = Json.Deserialize<HashParam>(strParam);
            string tttagKey = param.GetString("key");
            if (param.ContainsKey("IDs"))
            {
                string ids = param.GetString("IDs");
                string[] _inventoryIDs = ids == null ? "0".Split(',') : ids.TrimEnd(',').Split(',');
                int[] InventoryIDs = new int[_inventoryIDs.Length];
                for (int i = 0; i < _inventoryIDs.Length; i++)
                {
                    InventoryIDs[i] = Convert.ToInt32(_inventoryIDs[i]);//不能为空
                }
                TransmissionOrderResult delOrderResult = AllPublic.OprationOrders(InventoryIDs, "del", tttagKey);//OprationOrders 删除订单 ]
                return JsonConvert.SerializeObject(delOrderResult);
            }
            else
                return "未找到标识IDs";
        }
        #endregion



        #region &&&&&&&&&&&&&&&&&&&&&销售报告&&&&&&&&&&&&&&&&&&&&&一共 5 个子模块：访问，订单，利润，延期，资产
        //访问    /api/report/visit
        public static string ReportAboutVisit(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "销售报告访问量");
            var result = GetRequest(GlobalConfig.SalesReportVisitUrl, tttagKey);
            return result;
        }
        //订单   /api/report/order
        public static string ReportAboutOrder(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "销售报告订单");
            var result = GetRequest(GlobalConfig.SalesReportOrderUrl, tttagKey);
            return result;
        }
        //利润    /api/report/profit
        public static string ReportAboutProfit(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "销售报告利润");
            var result = GetRequest(GlobalConfig.SalesReportProfitUrl, tttagKey);
            return result;
        }
        //延期    /api/report/delay
        public static string ReportAboutDelay(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "销售报告延期");
            var result = GetRequest(GlobalConfig.SalesReportDelayUrl, tttagKey);
            return result;
        }
        //资产    /api/report/assets
        public static string ReportAboutAssets(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "销报告资产");
            var result = GetRequest(GlobalConfig.SalesReportAssetsUrl, tttagKey);
            return result;
        }
        public static string GetRequest(string url, string key)
        {
            //key = "YIYI"; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
            return MyHttpRequest.HttpRequest(url + "?hostname=" + key, "", "", "get");
        }
        //价格报告增加这两个字段，需求退点，pointer数据更新时间。 
        // /dpi/pointer?is_fancy=0&shape=1&weight_start=0.30&color=D&clarity=VVS2&cut_class=EX&fluorescence_class=N&cert_type=GIA 
        public static string GetDpiPointer(string strParam)
        {
            var logParam = strParam;
            HashParam param = Json.Deserialize<HashParam>(strParam);
            string tttagKey = CommonUrl.getURL(param, strParam, "获取价格报告增加这两个字段");
            HashParam newParam = new HashParam();
            string paramString = "";
            {
                if (param.ContainsKey("is_fancy"))
                {
                    paramString += "&is_fancy=" + param.GetString("is_fancy");
                    newParam.Add("is_fancy", param.GetString("is_fancy"));
                }
                if (param.ContainsKey("shape"))
                {
                    paramString += "&shape=" + param.GetString("shape");
                    newParam.Add("shape", param.GetString("shape"));
                }
                if (param.ContainsKey("weight_start"))
                {
                    paramString += "&weight_start=" + param.GetString("weight_start");
                    newParam.Add("weight_start", param.GetString("weight_start"));
                }
                if (param.ContainsKey("color"))
                {
                    paramString += "&color=" + param.GetString("color");
                    newParam.Add("color", param.GetString("color"));
                }
                if (param.ContainsKey("clarity"))
                {
                    paramString += "&clarity=" + param.GetString("clarity");
                    newParam.Add("clarity", param.GetString("clarity"));
                }
                if (param.ContainsKey("cut_class"))
                {
                    paramString += "&cut_class=" + param.GetString("cut_class");
                    newParam.Add("cut_class", param.GetString("cut_class"));
                }
                if (param.ContainsKey("fluorescence_class"))
                {
                    paramString += "&fluorescence_class=" + param.GetString("fluorescence_class");
                    newParam.Add("fluorescence_class", param.GetString("fluorescence_class"));
                }
                if (param.ContainsKey("cert_type"))
                {
                    paramString += "&cert_type=" + param.GetString("cert_type");
                    newParam.Add("cert_type", param.GetString("cert_type"));
                }
            }
            paramString = "?" + paramString.TrimStart('&');
            #region 获取价格报告增加这两个字段
            string guid = Guid.NewGuid().ToString();
            int totalSeconds;
            string signStr;
            var objParams = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(newParam));
            var lastStr = MyHttpRequest.NestedDictSort2Str(objParams);
            MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr, "img");  //这里的id不是参数，所以签名不加入任何参数
            RequestInfo rif = new RequestInfo() { RequestUrl = GlobalConfig.SalesDpiPointerUrl + paramString }; //需要更新地址中的ID
            var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.GET); // 
            CommonLog.SendMQMsg(tttagKey, "获取pointer rap 价格参考数据：请求地址" + GlobalConfig.SalesDpiPointerUrl + paramString);
            return responseJson; //返回结果
            #endregion
        }
        #endregion &&&&&&&&&&&&&&&&&&&&&销售报告&&&&&&&&&&&&&&&&&&&&&


        public static bool CheckSql(string sql)
        {
            bool isPass = false;
            //还得继续加防止注入的关键字
            if (!sql.Contains("union") && !sql.Contains("order by") && !sql.Contains("--"))
            {
                isPass = true;
            }
            //order by
            return isPass;
        }

        /// <summary>
        ///修改网站对应的联系方式链接（qq,skype）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string UpdateLink(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param, "修改网站对应的联系方式链接");
            bool b = false;
            try
            {
                Link link = JsonConvert.DeserializeObject<Link>(param);
                b = YZ.GetDatabase(tttagKey).Edit(link) > 0;
                if (b)
                {
                    CommonLog.SendMQMsg(tttagKey, "修改网站对应的联系方式链接成功");
                    return "{\"message\":\"修改成功\",\"result\":\"" + b.ToString() + "\"}";
                }
                else
                    return "{\"message\":\"修改失败\",\"result\":\"" + b.ToString() + "\"}";
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                CommonLog.SendMQMsg(tttagKey, "异常信息：修改网站对应的联系方式链接" + ex.StackTrace + "参数:" + logParam);
                return "{\"message\":\"错误\",\"result\":\"" + b.ToString() + "\"}";
            }
        }
        #region 网站对应的联系方式链接（qq,skype）
        //查询
        public static string GetLink(string param)
        {
            var logParam = param;
            string tttagKey = CommonUrl.getURL(null, param);
            Link link = YZ.GetDatabase(tttagKey).QueryForObject<Link>("Link.GetLink", null);
            if (link == null)
            {
                return "{}";
            }
            else
            {
                if (logParam.Contains("AppKey"))
                {
                    JsonSerializerSettings jsetting =
                    new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        ContractResolver = new DynamicContractResolver(new string[] { "HomeImg", "Logo", "ID" })
                    };
                    return JsonConvert.SerializeObject(link, jsetting);
                }
                else
                {
                    return JsonConvert.SerializeObject(link);
                }
            }
        }

        #endregion

        /// <summary>
        ///  Delete stocks/shelves/ 全部裸钻下架   ?IsFancy=1 全部彩钻下架
        /// </summary>
        /// <returns></returns>
        public static string OffShelves(string param)
        {
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(_param,"");
            //下架
            //#msg 和"#msg" 
            //参数可全空
            var partUrl = "";  //参数部分URL
            var lib = "0";//0白钻 ,1彩
            param = JsonConvert.SerializeObject(_param);
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                var lastStr = "";
                //是否传参
                if (_param.Count()>0)
                {
                    JObject obj = JsonConvert.DeserializeObject<JObject>(param);
                    lastStr = MyHttpRequest.NestedDictSort2Str(obj);
                    lib = obj["IsFancy"].ToString();
                    partUrl = "?IsFancy=" + lib;
                }
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);  // 
                RequestInfo rif = new RequestInfo() { RequestJson = param, RequestUrl = string.Format(GlobalConfig.OnShelvesOrOffShelvesUrl, partUrl) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.DELETE); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else if (responseJson.Contains("true"))
                {
                    responseJson = CommonLog.MsgSuccessInfo((partUrl == "" ? "全部" : lib == "0" ? "白钻" : "彩钻") + "下架成功");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo((partUrl == "" ? "全部" : lib == "0" ? "白钻" : "彩钻") + "下架失败，程序错误");
            }
        }
        public static string OnShelves(string param)
        {
            HashParam _param = JsonConvert.DeserializeObject<HashParam>(param);
            string tttagKey = CommonUrl.getURL(_param, "");
            //上架
            //#msg 和"#msg" 
            //参数可全空
            var partUrl = "";  //参数部分URL
            var lib = "0";//0白钻 ,1彩
            param = JsonConvert.SerializeObject(_param);
            try
            {
                string guid = Guid.NewGuid().ToString();
                int totalSeconds;
                var lastStr = "";
                //是否传参
                if (_param.Count()>0)
                {
                    JObject obj = JsonConvert.DeserializeObject<JObject>(param);
                    lastStr = MyHttpRequest.NestedDictSort2Str(obj);
                    lib = obj["IsFancy"].ToString();
                    partUrl = "?IsFancy=" + lib;
                }
                string signStr;
                MyHttpRequest.SignByParams(guid, lastStr, tttagKey, out totalSeconds, out signStr);  // 
                RequestInfo rif = new RequestInfo() { RequestJson = param, RequestUrl = string.Format(GlobalConfig.OnShelvesOrOffShelvesUrl, partUrl) }; //需要更新地址中的ID
                var responseJson = MyHttpRequest.PostJSONByRequestParam(rif, 3, guid, signStr, totalSeconds, null, MyHttpRequest.RequestLib.POST); //
                if (responseJson.Contains(".py"))
                {
                    responseJson = CommonLog.MsgErrorInfo("远程服务错误");
                }
                else if (responseJson.Contains("true"))
                {
                    responseJson = CommonLog.MsgSuccessInfo((partUrl == "" ? "全部" : lib == "0" ? "白钻" : "彩钻") + "上架成功");
                }
                return responseJson;
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo((partUrl == "" ? "全部" : lib == "0" ? "白钻" : "彩钻") + "上架失败，程序错误");
            }
        }

   
        /// <param name="user"></param>
        /// <param name="key"></param>
        /// <param name="customerId"></param>
        /// <param name="needSave"></param>
        /// <returns></returns>
        #region  小程序相关
        public static bool SaveWxUser(WechatXcxInfo user, string key, out int customerId, bool needSave = false)
        {
            customerId = 0;
            if (string.IsNullOrEmpty(key))
            {
                CLogger($"SaveWxUser:key{key}");
                return false;
            }

            if (needSave)
            {
                user.bind_time = DateTime.Now;
                return YZ.GetDatabase(key).Update("WxInfo.UpdateCustmoerId", user) > 0;
            }
            else
            {
                user.create_time = DateTime.Now;
                bool isSave = true;
                //是否存在
                WechatXcxInfo dbUser = GetWxUserByOpenid(user, key);
                if (dbUser == null)
                {
                    isSave = YZ.GetDatabase(key).Add(user) > 0;

                }
                else
                { 
                    customerId = dbUser.customer_id; 
                }
                return isSave;
            }
        }

        public static WechatXcxInfo GetWxUserByOpenid(WechatXcxInfo user, string key)
        {
            return string.IsNullOrEmpty(key) ? null : YZ.GetDatabase(key).QueryForObject<WechatXcxInfo>("WxInfo.GetUserByOpenid", user);
        }

        public static string CheckBindByParam(string user, string key)
        {
            //小程序检测绑定
            try
            {
                WechatXcxInfo param = JsonConvert.DeserializeObject<WechatXcxInfo>(user);
                //走保存流程
                SaveWxUser(param, key, out int customerId);
                var co = new { CustomerId = customerId, OpenId = param.openid };
                return CommonLog.MsgObj((customerId > 0), JsonConvert.SerializeObject(co));
            }
            catch (Exception ex)
            {
                GetMethodInfoAndWriteLogs(ex);
                return CommonLog.MsgErrorInfo("检查用户信息失败：" + ex.Message);
            }
        }
        /// <summary>
        /// 绑定客户信息
        /// </summary>
        /// <param name="user"></param>
        /// <param name="flag">2为团队绑定，1 为客户绑定</param>
        /// <returns></returns>
        public static string BindByParam(string customerAndOpenId, string key,int flag=1)
        {
            //小程序检测绑定
            try
            {
                HashParam param = JsonConvert.DeserializeObject<HashParam>(customerAndOpenId);
                if (!(param.ContainsKey("UserName") && param.ContainsKey("UserPassword") && param.ContainsKey("OpenId")))
                    return CommonLog.MsgErrorInfo("参数不正确");
                param["UserPassword"] = Yunzuan.Foundation.Safe.EncryptHelper.MD5(param.GetString("UserPassword"));
                var _id = 0;
                var nickName = "";
                if (flag == 1) //指客户绑定
                {
                    //用客户姓名密码查找客户信息
                    CustomerInfo customerInfo = YZ.GetDatabase(key).QueryForObject<CustomerInfo>("Customer.GetCustomerByUserNameAndUserPassword", param);
                    if (customerInfo == null)
                        return CommonLog.MsgErrorInfo("客户账号信息不正确");
                    _id = customerInfo.CustomerID;
                }
                else //团队
                {
                    //用客户姓名密码查找客户信息
                    UserInfo userinfo = YZ.GetDatabase(key).QueryForObject<UserInfo>("User.GetUserByUserNameAndUserPassword", param);
                    if (userinfo == null)
                        return CommonLog.MsgErrorInfo("客户账号信息不正确");
                    _id = userinfo.UserID;
                    nickName = userinfo.RealName;
                } 
                //账号正确的话就开始绑定 
                var wxInfo = GetWxUserByOpenid(new WechatXcxInfo() { openid = param.GetString("OpenId") }, key);
                if (wxInfo == null)
                    return CommonLog.MsgErrorInfo("用户未保存不能进行绑定");
                wxInfo.customer_id = _id;
                wxInfo.flag = flag;
                //保存小程序对应账号信息
                bool isSave = SaveWxUser(wxInfo, key, out int notused, true);
                if (isSave)
                {
                    if (flag == 1) //指客户绑定
                    {
                        return CommonLog.MsgSuccessInfo(wxInfo.customer_id.ToString());
                    }
                    else
                    {
                        //麦金麦钻需要返回业务昵称
                        var en = new { uid = wxInfo.customer_id.ToString(), nick = nickName };
                        return CommonLog.MsgObj(isSave, JsonConvert.SerializeObject(en));
                    }
                }
                else
                {
                    return CommonLog.MsgErrorInfo("绑定失败");
                }
            }
            catch (Exception ex)
            {
                return CommonLog.MsgErrorInfo("绑定客户信息失败：" + ex.Message);
            }
        }
        #endregion

        //日志
        public static void CLogger(string message)
        {
            Logger.Error(typeof(AllPublic), message);

        }
    }
}
